#include "serversocket.h"

ServerSocket::ServerSocket()
{
    int tr = 1;
    _connectionSocket = socket(AF_INET, SOCK_STREAM, 0);
    memset((char*)&serverAddress,'\0',sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(4242);

    if(setsockopt( _connectionSocket,SOL_SOCKET, SO_REUSEADDR, &tr, sizeof(int) ) == -1 ) return;
    if(setsockopt( _connectionSocket, IPPROTO_TCP, TCP_NODELAY, &tr, sizeof(int) ) == -1 ) return;

    if(bind ( _connectionSocket, (struct sockaddr * ) &serverAddress, sizeof(serverAddress) ) < 0) return;
};

void ServerSocket::listenConnection(int n) {
    listen(_connectionSocket, n);
};

int ServerSocket::acceptConnection() {
    _clilen = sizeof(clientAddress);
    int tr = 1;
    _newConnectionSocket = accept( _connectionSocket, (struct sockaddr *) &clientAddress, &_clilen);
    setsockopt(_newConnectionSocket, IPPROTO_TCP, TCP_NODELAY, &tr, sizeof(int));
    return _newConnectionSocket;
};

void ServerSocket::errorClose() {
    shutdown(_newConnectionSocket, SHUT_RDWR);
    pthread_exit(NULL);
}
